﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QJY.Common;
using QJY.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace QJY.API
{


    #region 流程处理模块

    public class Yan_WF_DaiLiB : BaseEFDao<Yan_WF_DaiLi>
    { }

    public class Yan_WF_TDB : BaseEFDao<Yan_WF_TD>
    {

    }
    public class Yan_WF_PDB : BaseEFDao<Yan_WF_PD>
    {
        /// <summary>
        ///获取流程Id
        /// </summary>
        /// <param name="processId"></param>
        /// <returns></returns>
        public int GetProcessID(string processName)
        {
            return new Yan_WF_PDB().GetEntity(d => d.ProcessName == processName).ID;
        }
    }



    public class Yan_WF_PIB : BaseEFDao<Yan_WF_PI>
    {
        /// <summary>
        /// 添加流程()
        /// </summary>
        /// <param name="strAPPCode"></param>
        /// <param name="strSHR"></param>
        /// <returns>返回创建的第一个任务</returns>
        public Yan_WF_TI StartWF(Yan_WF_PD PD, string strModelCode, string userName, string strSHR, string strCSR, Yan_WF_PI PI, ref List<string> ListNextUser)
        {



            if (PD.ProcessType == "-1")
            {
                ENDWF(PI.ID);
            }//没有流程步骤的,直接结束流程


            //创建流程实例
            Yan_WF_TI TI = new Yan_WF_TI();
            if (PD.ProcessType == "1")//固定流程
            {
                //添加首任务
                TI.TDCODE = PI.PDID.ToString() + "-1";
                TI.PIID = PI.ID;
                TI.StartTime = DateTime.Now;
                TI.EndTime = DateTime.Now;
                TI.TaskUserID = userName;
                TI.TaskUserView = "发起表单";
                TI.TaskState = 1;//任务已结束
                TI.ComId = PD.ComId;
                TI.CRUser = userName;
                TI.CRDate = DateTime.Now;
                TI.TaskName = "发起表单";
                TI.PreTaskInstance = PI.Content;
                new Yan_WF_TIB().Insert(TI);
                //添加首任务
                ListNextUser = AddNextTask(TI, userName);

            }
            return TI;

        }



        /// <summary>
        /// 结束当前任务
        /// </summary>
        /// <param name="TaskID"></param>
        /// <param name="strManAgeUser"></param>
        /// <param name="strManAgeYJ"></param>
        private void ENDTASK(int TaskID, string strManAgeUser, string strManAgeYJ, string strPIContent, int Status = 1)
        {
            Yan_WF_TI TI = new Yan_WF_TIB().GetEntity(d => d.ID == TaskID);
            TI.TaskUserID = strManAgeUser;
            TI.TaskUserView = strManAgeYJ;
            TI.EndTime = DateTime.Now;
            TI.TaskState = Status;
            TI.PreTaskInstance = strPIContent;
            new Yan_WF_TIB().Update(TI);
            new Yan_WF_PIB().ExsSclarSql("UPDATE Yan_WF_TI SET TaskState=" + Status + " WHERE PIID='" + TI.PIID + "' AND TDCODE='" + TI.TDCODE + "'");//将所有任务置为结束状态
        }

        /// <summary>
        /// 结束当前流程
        /// </summary>
        /// <param name="PID"></param>
        public void ENDWF(int PID)
        {
            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == PID);
            PI.isComplete = "Y";
            PI.CompleteTime = DateTime.Now;
            new Yan_WF_PIB().Update(PI);
        }


        /// <summary>
        /// 添加下一任务节点
        /// </summary>
        /// <param name="PID"></param>
        private List<string> AddNextTask(Yan_WF_TI TI, string strCRUser)
        {
            List<string> ListNextUser = new List<string>();
            string strNextTcode = TI.TDCODE.Split('-')[0] + "-" + (int.Parse(TI.TDCODE.Split('-')[1]) + 1).ToString();//获取任务CODE编码,+1即为下个任务编码
            Yan_WF_TD TD = new Yan_WF_TD();
            TD = new Yan_WF_TDB().GetEntity(d => d.TDCODE == strNextTcode);
            if (TD != null)
            {
                Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == TI.PIID);
                if (TD.isSJ == "0")//选择角色时找寻角色人员
                {
                    DataTable dt = new JH_Auth_UserRoleB().GetUserDTByRoleCode(Int32.Parse(TD.AssignedRole), TI.ComId.Value);
                    foreach (DataRow dr in dt.Rows)
                    {
                        //部门限定为真时
                        if (TD.ProcessLogic == "1")
                        {
                            if (new JH_Auth_UserRoleB().IsSameOrg(PI.CRUser, dr["username"].ToString()))
                            {
                                Yan_WF_TI Node = new Yan_WF_TI();
                                Node.TDCODE = strNextTcode;
                                Node.PIID = TI.PIID;
                                Node.StartTime = DateTime.Now;
                                Node.TaskUserID = dr["username"].ToString();
                                Node.TaskState = 0;//任务待结束
                                Node.TaskName = TD.TaskName;
                                Node.TaskRole = TD.TaskAssInfo;
                                Node.ComId = TI.ComId;
                                Node.CRDate = DateTime.Now;
                                Node.CRUser = strCRUser;
                                new Yan_WF_TIB().Insert(Node);
                                ListNextUser.Add(dr["username"].ToString());
                            }
                        }
                        else
                        {
                            Yan_WF_TI Node = new Yan_WF_TI();
                            Node.TDCODE = strNextTcode;
                            Node.PIID = TI.PIID;
                            Node.StartTime = DateTime.Now;
                            Node.TaskUserID = dr["username"].ToString();
                            Node.TaskState = 0;//任务待结束
                            Node.TaskName = TD.TaskName;
                            Node.TaskRole = TD.TaskAssInfo;
                            Node.ComId = TI.ComId;
                            Node.CRDate = DateTime.Now;
                            Node.CRUser = strCRUser;

                            new Yan_WF_TIB().Insert(Node);
                            ListNextUser.Add(dr["username"].ToString());
                        }
                    }

                }
                if (TD.isSJ == "1")//选择上级时找寻上级
                {
                    string Leader = new JH_Auth_UserB().GetUserLeader(PI.ComId.Value, TI.TaskUserID);
                    if (!string.IsNullOrEmpty(TD.AssignedRole))
                    {
                        string strTempTCode = TD.ProcessDefinitionID + "-" + TD.AssignedRole;
                        List<Yan_WF_TI> tiModelSALL = new Yan_WF_TIB().GetEntities(d => d.PIID == PI.ID && d.TDCODE == strTempTCode && d.EndTime != null).OrderByDescending(D => D.EndTime).ToList();

                        if (tiModelSALL.Count > 0)
                        {
                            string strTempUser = tiModelSALL[0].TaskUserID;
                            foreach (Yan_WF_TI item in tiModelSALL)
                            {
                                if (!string.IsNullOrEmpty(item.zhuandanfrom))
                                {
                                    strTempUser = item.zhuandanfrom;
                                }
                            }
                            //如果指定了节点序号,找出对应序号的直属上级,默认先找第一个节点得转单人
                            Leader = new JH_Auth_UserB().GetUserLeader(PI.ComId.Value, strTempUser);
                        }
                    }
                    Yan_WF_TI Node = new Yan_WF_TI();
                    Node.TDCODE = strNextTcode;
                    Node.PIID = TI.PIID;
                    Node.StartTime = DateTime.Now;
                    Node.TaskUserID = Leader;
                    Node.TaskState = 0;//任务待结束
                    Node.TaskName = TD.TaskName;
                    Node.TaskRole = TD.TaskAssInfo;
                    Node.ComId = TI.ComId;
                    Node.CRDate = DateTime.Now;
                    Node.CRUser = strCRUser;

                    new Yan_WF_TIB().Insert(Node);
                    ListNextUser.Add(Leader);

                }
                if (TD.isSJ == "2")//选择发起人时找寻发起人
                {


                    Yan_WF_TI Node = new Yan_WF_TI();
                    Node.TDCODE = strNextTcode;
                    Node.PIID = TI.PIID;
                    Node.StartTime = DateTime.Now;
                    Node.TaskUserID = PI.CRUser;
                    Node.TaskState = 0;//任务待结束
                    Node.TaskName = TD.TaskName;
                    Node.TaskRole = TD.TaskAssInfo;
                    Node.ComId = TI.ComId;
                    Node.CRDate = DateTime.Now;
                    Node.CRUser = strCRUser;

                    new Yan_WF_TIB().Insert(Node);
                    ListNextUser.Add(PI.CRUser);
                }
                if (TD.isSJ == "3")//选择指定人员找指定人
                {
                    foreach (string user in TD.AssignedRole.TrimEnd(',').Split(','))
                    {

                        if (TD.ProcessLogic == "1")
                        {
                            if (new JH_Auth_UserRoleB().IsSameOrg(PI.CRUser, user))
                            {
                                Yan_WF_TI Node = new Yan_WF_TI();
                                Node.TDCODE = strNextTcode;
                                Node.PIID = TI.PIID;
                                Node.StartTime = DateTime.Now;
                                Node.TaskUserID = user;
                                Node.TaskState = 0;//任务待结束
                                Node.TaskName = TD.TaskName;
                                Node.TaskRole = TD.TaskAssInfo;
                                Node.ComId = TI.ComId;
                                Node.CRDate = DateTime.Now;
                                Node.CRUser = strCRUser;

                                new Yan_WF_TIB().Insert(Node);
                                ListNextUser.Add(user);
                            }
                        }
                        else
                        {
                            Yan_WF_TI Node = new Yan_WF_TI();
                            Node.TDCODE = strNextTcode;
                            Node.PIID = TI.PIID;
                            Node.StartTime = DateTime.Now;
                            Node.TaskUserID = user;
                            Node.TaskState = 0;//任务待结束
                            Node.TaskName = TD.TaskName;
                            Node.TaskRole = TD.TaskAssInfo;
                            Node.ComId = TI.ComId;
                            Node.CRDate = DateTime.Now;
                            Node.CRUser = strCRUser;

                            new Yan_WF_TIB().Insert(Node);
                            ListNextUser.Add(user);
                        }
                    }
                }
                if (TD.isSJ == "4")//选择绑定字段的值
                {
                    string strGLUser = new Yan_WF_PIB().GetFiledVal(PI.Content, TD.AssignedRole);

                    foreach (string user in strGLUser.TrimEnd(',').Split(','))
                    {
                        Yan_WF_TI Node = new Yan_WF_TI();
                        Node.TDCODE = strNextTcode;
                        Node.PIID = TI.PIID;
                        Node.StartTime = DateTime.Now;
                        Node.TaskUserID = user;
                        Node.TaskState = 0;//任务待结束
                        Node.TaskName = TD.TaskName;
                        Node.TaskRole = TD.TaskAssInfo;
                        Node.ComId = TI.ComId;
                        Node.CRDate = DateTime.Now;
                        Node.CRUser = strCRUser;

                        new Yan_WF_TIB().Insert(Node);
                        ListNextUser.Add(strGLUser);
                    }

                }

            }


            return ListNextUser;

        }
        /// <summary>
        /// 退回当前流程
        /// </summary>
        /// <param name="PID"></param>
        private void REBACKWF(int PID)
        {
            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == PID);
            PI.IsCanceled = "Y";
            PI.CanceledTime = DateTime.Now;
            new Yan_WF_PIB().Update(PI);

        }

        /// <summary>
        /// 获取需要处理的任务
        /// </summary>
        /// <param name="strUser">用户需要处理</param>
        /// <returns></returns>
        public List<Yan_WF_TI> GetDSH(JH_Auth_User User)
        {
            List<Yan_WF_TI> ListData = new List<Yan_WF_TI>();

            ListData = new Yan_WF_TIB().GetEntities("ComId ='" + User.ComId.Value + "' AND TaskUserID ='" + User.UserName + "'AND TaskState='0'").ToList();
            return ListData;
        }



        /// <summary>
        /// 判断当前用户当前流程是否可以审批
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public string isCanSP(string strUser, int PIID)
        {
            DataTable dt = new Yan_WF_TIB().GetDTByCommand("SELECT ID FROM  Yan_WF_TI  WHERE PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ");
            return dt.Rows.Count > 0 ? "Y" : "N";
        }





        /// <summary>
        /// 退回流程
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public bool REBACKLC(string strUser, int PIID, string strYJView)
        {
            try
            {
                Yan_WF_TI MODEL = new Yan_WF_TIB().GetEntities(" PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ").FirstOrDefault();
                if (MODEL != null)
                {
                    ENDTASK(MODEL.ID, strUser, strYJView, "", -1);//退回
                    REBACKWF(MODEL.PIID);
                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }

        /// <summary>
        /// 退回到上一步
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <param name="strYJView"></param>
        /// <returns></returns>
        public bool REBACKPREWF(string strUser, int PIID, string strYJView, ref string strTXUser)
        {
            try
            {
                Yan_WF_TI MODEL = new Yan_WF_TIB().GetEntities(" PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ").FirstOrDefault();
                if (MODEL != null)
                {
                    strTXUser = MODEL.CRUser;
                    Yan_WF_ChiTask ChiTask = new Yan_WF_ChiTask();
                    ChiTask.TaskInstanceID = MODEL.ID.ToString();
                    ChiTask.TaskUser = new JH_Auth_UserB().GetUserRealName(0, strUser);
                    ChiTask.Crdate = DateTime.Now;
                    ChiTask.CrUser = strUser;
                    ChiTask.ComId = "0";
                    ChiTask.IsHasManager = "退回上一步";
                    ChiTask.TaskInstanceID = MODEL.TDCODE;
                    ChiTask.Remark = MODEL.PIID.ToString();
                    ChiTask.UserView = strYJView;
                    new Yan_WF_ChiTaskB().Insert(ChiTask);

                    int PreTaskOrder = MODEL.TDCODE.SplitTOInt('-')[1] - 1;
                    string strPreTask = MODEL.TDCODE.SplitTOInt('-')[0].ToString() + "-" + PreTaskOrder.ToString();
                    new Yan_WF_TIB().Delete(D => D.TDCODE == MODEL.TDCODE && D.PIID == PIID);//删除本任务节点
                    new Yan_WF_PIB().ExsSclarSql("UPDATE yan_wf_ti SET EndTime = NULL,TaskUserView = NULL,TaskState = '0' WHERE PIID = '" + PIID + "'AND TDCODE = '" + strPreTask + "'");//返回上一节点为未处理状态


                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }





        /// <summary>
        /// 处理流程
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public bool MANAGEWF(string strUser, Yan_WF_PI PI, string strYJView, ref List<string> ListNextUser, ref string isTDComplete, ref string isSaveData, string strZShUser)
        {
            try
            {
                Yan_WF_TI MODEL = new Yan_WF_TIB().GetEntities(" PIID='" + PI.ID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ").FirstOrDefault();
                if (MODEL != null)
                {
                    Yan_WF_TD TD = new Yan_WF_TDB().GetEntities(D => D.TDCODE == MODEL.TDCODE).FirstOrDefault();

                    if (string.IsNullOrEmpty(strZShUser))
                    {
                        int TaskCount = new Yan_WF_TIB().GetEntities(D => D.PIID == PI.ID && D.TDCODE == TD.TDCODE && D.TaskState == 0).Count();
                        if (TaskCount > 1 && TD.AboutAttached == "1")
                        {
                            //会签，处理单个任务节点
                            isTDComplete = "N";
                            MODEL.TaskUserID = strUser;
                            MODEL.TaskUserView = strYJView;
                            MODEL.EndTime = DateTime.Now;
                            MODEL.TaskState = 1;
                            new Yan_WF_TIB().Update(MODEL);
                        }
                        else
                        {
                            isTDComplete = "Y";
                            ENDTASK(MODEL.ID, strUser, strYJView, PI.Content);
                            ListNextUser = AddNextTask(MODEL, strUser);
                            //循环找下一个审核人是否包含本人，如果包含则审核通过
                            //if (ListNextUser.Contains(strUser))
                            //{
                            //    ListNextUser.Clear();
                            //    return MANAGEWF(strUser, PI, strYJView, ref ListNextUser, ref isTDComplete, ref isSaveData, strZShUser);
                            //}
                        }
                    }
                    else
                    {
                        //转审,只更改 当前节点用户处理User
                        MODEL.TaskUserID = strZShUser;
                        MODEL.zhuandanfrom = strUser;
                        new Yan_WF_TIB().Update(MODEL);


                        Yan_WF_ChiTask ChiTask = new Yan_WF_ChiTask();
                        ChiTask.TaskInstanceID = MODEL.ID.ToString();
                        ChiTask.TaskUser = new JH_Auth_UserB().GetUserRealName(0, strUser);
                        ChiTask.Crdate = DateTime.Now;
                        ChiTask.CrUser = strUser;
                        ChiTask.ComId = "0";
                        ChiTask.IsHasManager = "转审";
                        ChiTask.TaskInstanceID = MODEL.TDCODE;
                        ChiTask.Remark = MODEL.PIID.ToString();
                        ChiTask.UserView = strYJView;
                        new Yan_WF_ChiTaskB().Insert(ChiTask);
                    }
                    if (!string.IsNullOrEmpty(TD.WritableFields))
                    {
                        isSaveData = "Y";//需要保存表单数据
                    }

                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }

        /// <summary>
        /// 已处理的任务
        /// </summary>
        /// <param name="strUser"></param>
        /// <returns></returns>
        public List<Yan_WF_TI> GetYSH(JH_Auth_User User)
        {
            List<Yan_WF_TI> ListData = new List<Yan_WF_TI>();
            ListData = new Yan_WF_TIB().GetEntities(" ComId ='" + User.ComId.Value + "' AND TaskUserID ='" + User.UserName + "' AND (TaskState=1 OR TaskState=-1) AND TaskUserView!='发起表单'").ToList();
            return ListData;
        }


        public int GETPDID(int PIID)
        {
            Yan_WF_PI pi = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);
            return pi == null ? 0 : pi.PDID.Value;
        }


        /// <summary>
        /// 更具PID获取PD数据
        /// </summary>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public Yan_WF_PD GETPDMODELBYID(int PIID)
        {
            Yan_WF_PD MODEL = new Yan_WF_PD();
            Yan_WF_PI pi = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);
            if (pi != null)
            {
                MODEL = new Yan_WF_PDB().GetEntity(d => d.ID == pi.PDID);
            }

            return MODEL;
        }



        /// <summary>
        /// 根据数据ID进行归档操作
        /// </summary>
        /// <param name="modelCode">modelCode</param>
        /// <param name="PIID">流程的PIID</param>
        /// <returns></returns>
        public void GDForm(string isGD, int ComID, string PIIDS)
        {
            string strSql = string.Format(" UPDATE Yan_WF_PI SET isGD='{0}',GDDate='{1}' where Comid='{2}' AND  ID in ({3})", isGD, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ComID.ToString(), PIIDS);
            object obj = new Yan_WF_PIB().ExsSclarSql(strSql);

        }






        /// <summary>
        /// 根据PIID判断当前流程的数据（）
        /// </summary>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public Yan_WF_TD GetPDStatus(int PIID)
        {
            Yan_WF_TI Model = new Yan_WF_TIB().GetEntities(d => d.PIID == PIID).OrderByDescending(d => d.ID).FirstOrDefault();
            Yan_WF_TD TD = new Yan_WF_TD();
            if (Model != null)
            {
                TD = new Yan_WF_TDB().GetEntities(D => D.TDCODE == Model.TDCODE).FirstOrDefault();

            }
            else
            {
                TD = new Yan_WF_TDB().GetEntities(D => D.ProcessDefinitionID == 257).FirstOrDefault();

            }
            return TD;
        }

        /// <summary>
        /// 判断当前用户当前流程是否可以撤回和更新,判断是不是只有一个处理过得节点，或者是自己创建的无流程的表单,或者拥有管理权限得单据
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns>返回Y得时候可以撤回,返回不是Y,代表已经处理了不能撤回</returns>
        public string isCanCancel(string strUser, Yan_WF_PI PIMODEL,string strQXJGCode)
        {
            string strReturn = "N";

            DataTable dt = new Yan_WF_TIB().GetDTByCommand("SELECT * FROM  Yan_WF_TI  WHERE PIID='" + PIMODEL.ID + "' AND EndTime IS not null");
            if (dt.Rows.Count == 1 && dt.Rows[0]["TaskUserID"].ToString() == strUser)
            {
                strReturn = "Y";
            }
            if (PIMODEL.CRUser == strUser && PIMODEL.PITYPE == "-1")
            {
                //自己创建的无流程的表单
                strReturn = "Y";

            }
            if (strQXJGCode.SplitTOList(',').Contains(PIMODEL.BranchNO.ToString()) && PIMODEL.PITYPE == "-1")
            {
                //自己创建的无流程的表单,并且属于权限部门下得用户创建得数据
                strReturn = "Y";

            }
            return strReturn;
        }


        /// <summary>
        /// 删除流程及相关表单数据（事务执行）
        /// </summary>
        /// <param name="PIMODEL"></param>
        /// <returns></returns>
        public string CanCancel(int PIID, string strUserName, string UserBMQXCode, string isforce = "N")
        {
            string strReturn = "";

            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);
            Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == PI.PDID);

            string strISCanCel = new Yan_WF_PIB().isCanCancel(strUserName, PI, UserBMQXCode);
            if (strISCanCel == "N" && isforce=="N")
            {
                
                strReturn = "该表单已处理完毕,您无法再进行撤回操作";
            }
            else
            {
                //可以根据强制删除标记强制删除
                var result = Db.Ado.UseTran(() =>
                {
                    Db.Deleteable<Yan_WF_PI>().Where(it => it.ID == PIID).ExecuteCommand();
                    Db.Deleteable<Yan_WF_TI>().Where(it => it.ID == PIID).ExecuteCommand();
                    Db.Deleteable<JH_Auth_ExtendData>().Where(it => it.DataID == PIID).ExecuteCommand();
                    if (!string.IsNullOrEmpty(PD.RelatedTable))
                    {
                        Db.Ado.ExecuteCommand("DELETE FROM " + PD.RelatedTable + " WHERE intProcessStanceid = " + PI.ID.ToString());
                    }

                });
                if (!result.IsSuccess)
                {
                    strReturn = result.ErrorMessage;
                }
            }
            return strReturn;
        }


        /// <summary>
        /// 删除流程及相关表单数据（事务执行）,通过ID删除(风险较大,是不是得添加权限控制)//废弃
        /// </summary>
        /// <param name="PIMODEL"></param>
        /// <returns></returns>
        public string DeFormData(string Table, string DataIDS)
        {
            string strReturn = "";
            DataTable dt = this.GetDTByCommand("select ID,intProcessStanceid from " + Table + " WHERE ID IN ('" + DataIDS.ToFormatLike() + "')");
            var result = Db.Ado.UseTran(() =>
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int DataID = int.Parse(dt.Rows[i]["ID"].ToString());
                    int Pid = int.Parse(dt.Rows[i]["intProcessStanceid"].ToString());
                    Db.Ado.ExecuteCommand("DELETE FROM " + Table + " WHERE ID = " + DataID);
                    if (Pid != 0)
                    {
                        Db.Deleteable<Yan_WF_PI>().Where(it => it.ID == Pid).ExecuteCommand();
                        Db.Deleteable<Yan_WF_TI>().Where(it => it.ID == Pid).ExecuteCommand();
                        Db.Deleteable<JH_Auth_ExtendData>().Where(it => it.DataID == Pid).ExecuteCommand();
                    }

                }
            });
            if (!result.IsSuccess)
            {
                strReturn = result.ErrorMessage;
            }
            return strReturn;
        }


        /// <summary>
        /// 生成流水号
        /// </summary>
        /// <param name="PIMODEL"></param>
        /// <returns></returns>
        public string CreateWFNum(string PDID, string strQZ = "0")
        {
            string strReturn = "";
            DataTable dt = new Yan_WF_TIB().GetDTByCommand(" select ISNULL(max(WFFormNum),0) as MAXFORMMUM from Yan_WF_PI WHERE PDID = '" + PDID + "'");
            strReturn = CommonHelp.GetWFNumber(dt.Rows[0][0].ToString(), PDID, strQZ);
            return strReturn;
        }


        /// <summary>
        /// 从PI数据中获取关联字段的值，主要是关联审批人
        /// </summary>
        /// <param name="Content"></param>
        /// <returns></returns>
        public string GetFiledVal(string Content, string wigdetcode, string strValueText = "0")
        {
            string strReturn = "";
            try
            {
                JArray datas = (JArray)JsonConvert.DeserializeObject(Content);
                foreach (JObject item in datas)
                {
                    if ((string)item["wigdetcode"].ToString() == wigdetcode)
                    {
                        if (strValueText == "0")
                        {
                            strReturn = (string)item["value"].ToString();

                        }
                        else
                        {
                            strReturn = (string)item["valuetext"].ToString();

                        }

                    }
                }
            }
            catch (Exception)
            {
                strReturn = "";
            }

            return strReturn;
        }

        public string GetFiledValByFiled(string Content, string fild, string strValueText = "0")
        {
            string strReturn = "";
            try
            {
                JArray datas = (JArray)JsonConvert.DeserializeObject(Content);
                foreach (JObject item in datas)
                {
                    if ((string)item["glfiled"].ToString() == fild)
                    {
                        if (strValueText == "0")
                        {
                            strReturn = (string)item["value"].ToString();

                        }
                        else
                        {
                            strReturn = (string)item["valuetext"].ToString();

                        }

                    }
                }
            }
            catch (Exception)
            {
                strReturn = "";
            }

            return strReturn;
        }




        /// <summary>
        /// 导出专用
        /// </summary>
        /// <param name="Content"></param>
        /// <param name="wigdetcode"></param>
        /// <returns></returns>
        public string GetFiledValByDC(string Content, string wigdetcode)
        {
            string strReturn = "";
            try
            {
                JArray datas = (JArray)JsonConvert.DeserializeObject(Content);
                foreach (JObject item in datas)
                {
                    if ((string)item["wigdetcode"].ToString() == wigdetcode)
                    {
                        strReturn = (string)item["value"].ToString();
                        if (item["wigdetcode"].ToString().Contains("Edit"))
                        {
                            strReturn = System.Text.RegularExpressions.Regex.Replace(strReturn, "<[^>]+>", "");
                            System.Text.RegularExpressions.Regex.Replace(strReturn, "&[^;]+;", "");
                        }
                        if (item["wigdetcode"].ToString().Contains("Select"))
                        {
                            strReturn = (string)item["valuetext"].ToString();
                        }

                    }
                }
            }
            catch (Exception)
            {
                strReturn = "";
            }

            return strReturn;
        }


        /// <summary>
        /// 获取流程待处理节点序号
        /// </summary>
        /// <param name="strPI"></param>
        /// <returns></returns>
        public string GetPITaskOrder(int strPI)
        {
            string strOrder = "0";
            Yan_WF_TI ti = new Yan_WF_TIB().GetEntities(D => D.PIID == strPI).OrderByDescending(D => D.ID).FirstOrDefault();
            if (ti != null)
            {
                strOrder = ti.TDCODE.Split('-')[1];
            }

            return strOrder;
        }


    }

    public class Yan_WF_TIB : BaseEFDao<Yan_WF_TI> { }
    public class SZHL_DRAFTB : BaseEFDao<SZHL_DRAFT> { }


    public class Yan_WF_ChiTaskB : BaseEFDao<Yan_WF_ChiTask>
    {

    }

    #endregion


}
